# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day17_游于艺.py
# @ Time: 2018/3/9 12:30

"""
1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
 第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时
"""
def mk_sum():
    return sum(range(1,99999))
import time
# 第一：重复10次计算总时间
def count10():
    time1 = time.time()
    for i in range(10):
        mk_sum()
    time2 = time.time()
    print("重复10次计算总时间为：{}".format(time2-time1))

# 第二：开启十个子线程去计算;
from threading import Thread,current_thread
def thr10():
    time1 = time.time()
    thread_list = [Thread(target=mk_sum,args=()) for num in range(10)]
    for thr in thread_list:
        thr.start()
        thr.join()
    time2 = time.time()
    print("开启十个子线程计算总时间为：{}".format(time2 - time1))

# 第三:开启十个进程去计算
from multiprocessing import Process,Pool
def pro10():
    time1 = time.time()
    pro = Process(target=mk_sum, args=())
    pro.start()
    pro.join()
    time2 = time.time()
    print("开启十个进程计算总时间为：{}".format(time2 - time1))

# 开启进程池
def pro_pool(cpunum):
    time1 = time.time()
    pool = Pool(cpunum) #最大进程数目
    for num in range(cpunum):
        pool.apply_async(mk_sum,args=())
    pool.close()
    pool.join()
    time2 = time.time()
    print("进程池计算总时间为：{}".format(time2 - time1))
if __name__ == '__main__':
    count10() #重复10次
    thr10() #十个线程跑
    pro10() #十个进程跑
#     进程池
    pro_pool(4)



# 耗时结论：十个进程跑 > 十个线程跑 > 重复10次 > 进程池
"""
2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定

【见上面】
"""
